let urls;

function getUrlList() {
    fetch(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/IPCLiveServer/list')
        .then(response => {
            if (!response.ok) {
                throw new Error('http error: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            urls = data;
            playVideos();
        })
        .catch(error => {
            console.error('error fetching data:', error);
        });
}

getUrlList();

const gridContainer = document.querySelector('div[class="grid-container"]');

function playVideos() {
    urls.forEach((url, index) => {
        const videoContainer = document.createElement('div');
        videoContainer.className = 'video-container';
        const videoPlayer = document.createElement('video');
        videoPlayer.className = 'video-player';
        videoPlayer.muted = true;
        videoPlayer.autoplay = true;
        videoContainer.appendChild(videoPlayer);
        gridContainer.appendChild(videoContainer);
        setTimeout(() => {
            playerStart(url, videoPlayer);
        }, index * 500);
    });
}

function playerStart(url, videoPlayer) {
    let player = mpegts.createPlayer({
        type: 'flv',
        isLive: true,
        hasAudio: false,
        hasVideo: true,
        url: 'ws://' + window.location.hostname + ':' + window.location.port + '/IPCLiveServer/websocket/live?' + url
    }, {
        enableWorker: true,
        enableStashBuffer: false,
        stashInitialSize: 128,
        liveBufferLatencyChasing: true,
        autoCleanupSourceBuffer: true,
        autoCleanupMaxBackwardDuration: 20,
        autoCleanupMinBackwardDuration: 10
    });
    mpegts.LoggingControl.enableAll = false;
    player.attachMediaElement(videoPlayer);
    player.load();
    player.play();
}